package com.fc.campusapplicationsystem.controller;

import com.fc.campusapplicationsystem.model.Consumer;
import com.fc.campusapplicationsystem.model.Feedback;
import com.fc.campusapplicationsystem.service.FeedbackService;
import com.fc.campusapplicationsystem.util.ResponseOBJ;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 贺哲
 * @2020-02-29 15:28
 */
@RestController
@RequestMapping("/feedbackController")
public class FeedbackController {

    @Autowired
    FeedbackService feedbackService;

    @GetMapping("/list")
    public ResponseOBJ<List<Feedback>> list(@RequestParam("page") Integer page,
                                            @RequestParam("limit") Integer limit) {
        ResponseOBJ<List<Feedback>> responseOBJ = ResponseOBJ.getInstance();
        try {
            PageHelper.startPage(page, limit);
            List<Feedback> feedbacks = feedbackService.list();
            PageInfo<Feedback> pageInfo = new PageInfo<>(feedbacks);
            responseOBJ.setData(feedbacks);
            responseOBJ.setCount(pageInfo.getTotal());
            responseOBJ.setMsg("查询成功");
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            responseOBJ.setMsg("查询失败");
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }

    @GetMapping("/getAll")
    public ResponseOBJ<List<Feedback>> getAll(){
        ResponseOBJ<List<Feedback>> responseOBJ = ResponseOBJ.getInstance();
        try {
            responseOBJ.setData(feedbackService.getAll());
            responseOBJ.setMsg("查询成功");
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            responseOBJ.setMsg("查询失败");
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }









    /**
     * Feedback  给一个conten就可以了
     *
     * @param feedback
     * @return
     */
    @PostMapping("/add")
    public ResponseOBJ<Integer> add(@RequestBody Feedback feedback, HttpServletRequest request) {
        ResponseOBJ<Integer> responseOBJ = ResponseOBJ.getInstance();
        HttpSession session = request.getSession(true);
        Consumer consumer = (Consumer) session.getAttribute("consumer");
        feedback.setUserId(consumer.getId());
        try {
            Integer result = feedbackService.add(feedback);
            responseOBJ.setData(result);
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }
}
